package com.xiaobai.mall.index.web.controller;

import com.xiaobai.mall.cache.ICache;
import com.xiaobai.mall.cache.exception.CacheException;
import com.xiaobai.mall.index.api.IUserService;
import com.xiaobai.mall.index.domain.User;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Optional;
import java.util.UUID;

@RestController
@RequestMapping("/account")
public class LoginController {

    @Resource
    ICache cache;

    @Resource
    IUserService userService;

    @GetMapping("/login")
    public String login(String username, String password, HttpServletResponse response) throws CacheException {
        Assert.notNull(username, "用户名不能为空");
        Assert.notNull(password, "密码不能为空");
        User user = Optional.ofNullable(userService.queryUserByName(username)).filter(e -> password.equals(e.getPassword())).orElseThrow(() -> new IllegalArgumentException("账密错误"));
        String sessionId = UUID.randomUUID().toString();
        cache.set(sessionId, user);
        response.setHeader("sessionId", sessionId);
        response.addCookie(new Cookie("sessionId", sessionId));
        return "success";
    }

}
